<template>
  <view class="uni-container">
    <uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
      <uni-forms-item name="postName" label="房屋名称" required>
        <uni-easyinput placeholder="房屋名称" v-model="formData.postName"></uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="userPhone" label="租客联系电话" required>
        <uni-easyinput placeholder="租客联系电话" v-model="formData.userPhone"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="userName" label="租客姓名" required>
        <uni-easyinput placeholder="租客姓名" v-model="formData.userName"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="amount" label="月数" required>
	    <uni-easyinput placeholder="月数" type="number" v-model="formData.amount"></uni-easyinput>
	  </uni-forms-item>
	  <uni-forms-item name="pricePerMonth" label="月租金">
	    <uni-easyinput placeholder="月租金" v-model="formData.pricePerMonth"></uni-easyinput>
	  </uni-forms-item>
      <uni-forms-item name="price" label="总价">
        <uni-easyinput placeholder="总价" type="number" v-model="formData.price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="deposit" label="押金" required>
        <uni-easyinput placeholder="押金" type="number" v-model="formData.deposit"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="rentStart" label="租房日期" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.rentStart"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="rentEnd" label="结束日期" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.rentEnd"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="nextChargeTime" label="下次缴费日期" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.nextChargeTime"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="priceType" label="交租类型">
        <uni-data-checkbox v-model="formData.priceType" :localdata="formOptions.priceType_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="contract" label="合同">
<!--        <uni-file-picker return-type="object" v-model="formData.contract"></uni-file-picker>-->
        <upload-image return-type="object"  @choose="uploadContract()" :filesList="formData.contractList" @uploadFiles="uploadContract()"></upload-image>

      </uni-forms-item>
      <uni-forms-item name="remark" label="备注">
        <uni-easyinput placeholder="备注" v-model="formData.remark"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="订单状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="userIdcard" label="租客证件号">
        <uni-easyinput placeholder="租客证件号" v-model="formData.userIdcard"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="idcardUrl" label="租客证件照">
<!--        <uni-file-picker return-type="object" v-model="formData.idcardUrl"></uni-file-picker>-->
        <upload-image return-type="object" v-model="formData.idcardUrlList" @choose="uploadIdCardUrl()" :filesList="formData.idcardUrlList" @uploadFiles="uploadIdCardUrl()"></upload-image>
      </uni-forms-item>

      <uni-forms-item name="netFee" label="网费">
        <uni-easyinput placeholder="网费" v-model="formData.netFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="waterFee" label="水费">
        <uni-easyinput placeholder="水费" v-model="formData.waterFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="fireFee" label="燃气费">
        <uni-easyinput placeholder="燃气费" v-model="formData.fireFee"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="fireFee" label="物业费">
	    <uni-easyinput placeholder="物业费" v-model="formData.propertyFee"></uni-easyinput>
	  </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" @click="submit">提交</button>
        <button type="primary" class="uni-button" style="display: none" @click="submit">提醒缴费</button>
        <button type="primary" class="uni-button" style="display: none" @click="">新增租客</button>
      </view>

    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/order.js';
  import UploadImage from "../../uni_modules/uni-file-picker/components/uni-file-picker/upload-image";

  const db = uniCloud.database();
  const dbCollectionName = 'order';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    components: {UploadImage},
    data() {
      let formData = {
        "id": null,
        "postName": "",
        "amount": null,
        "userPhone": "",
        "userName": "",
        "price": null,
        "deposit": null,
        "rentStart": null,
        "rentEnd": null,
        "nextChargeTime": null,
        "priceType": 1,
        "contract": "",
        "contractList": [],
        "remark": "",
        "status": 0,
        "userIdcard": "",
        "idcardUrl": "",
        "idcardUrlList": [],
        "pricePerMonth": null,
        "netFee": null,
        "waterFee": null,
        "fireFee": null,
        "propertyFee": null
      }
      return {
        formData,
        formOptions: {
          "priceType_localdata": [
            {
              "text": "月付",
              "value": 1
            },
            {
              "text": "季付",
              "value": 2
            },
            {
              "text": "半年付",
              "value": 3
            },
            {
              "text": "年付",
              "value": 4
            }
          ],
          "status_localdata": [
            {
              "text": "进行中",
              "value": 0
            },
            {
              "text": "已结束",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        console.log(id)
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },


      /**
       * 提交表单
       */
      submitForm(value) {
        let _this = this
        //进行消息的订阅
        this.sub().then(()=>{
          _this.formData.contract = JSON.stringify(_this.formData.contractList);
          _this.formData.idcardUrl = JSON.stringify(_this.formData.idcardUrlList);
          return _this.$u.api.order.update(_this.formData).then((res) =>{
            uni.showToast({
              icon: 'none',
              title: '编辑成功'
            })
            _this.getOpenerEventChannel().emit('refreshData')
            setTimeout(() => uni.navigateBack(), 500)
          }).catch((err) => {
            uni.showModal({
              content: err.message || '请求服务失败',
              showCancel: false
            })
          })
        })

      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        this.$u.api.order.form(this.formDataId).then((resp) => {
          if (resp.code == '200') {
            this.formData = resp.data
            if (this.formData.hasOwnProperty("contract") && this.formData.contract) {
              this.formData.contractList = JSON.parse(this.formData.contract);
            } else {
              this.formData.contractList = [];
            }
            if (this.formData.hasOwnProperty("idcardUrl") &&  this.formData.idcardUrl) {
              this.formData.idcardUrlList = JSON.parse(this.formData.idcardUrl);
            } else if (!this.formData.idcardUrl) {
              this.formData.idcardUrlList = [];
            }
          }
        }).catch((e) =>{
          console.log(e)
        }).finally(
            () =>{
              uni.hideLoading()
            }
        )
      },
      uploadContract() {
        let url = "https://chenchao.pro/prod-api/common/upload";

        var that = this;
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album','camera'], //从相册选择
          success: function (res) {
            const tempFilePaths = res.tempFilePaths;
            //图片上传
            uni.uploadFile({
              url: url,
              filePath: tempFilePaths[0],
              name: 'file',
              file: {name: "file", uri: tempFilePaths[0]},
              header: {
                "Authorization": that.vuex_token
              },
              success: function (res) {
                const back = JSON.parse(res.data);
                that.formData.contractList.push(back)
				that.$forceUpdate();
              },
              fail: function (e) {
                console.log(e)
              }
            })
          },
          error : function(e){
            console.log(e);
          }
        });
      },
      uploadIdCardUrl() {
        let url = "https://chenchao.pro/prod-api/common/upload";

        var that = this;
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album','camera'], //从相册选择
          success: function (res) {
            const tempFilePaths = res.tempFilePaths;
            //图片上传
            uni.uploadFile({
              url: url,
              filePath: tempFilePaths[0],
              name: 'file',
              file: {name: "file", uri: tempFilePaths[0]},
              header: {
                "Authorization": that.vuex_token
              },
              success: function (res) {
                const back = JSON.parse(res.data);
                that.formData.idcardUrlList.push(back)
				that.$forceUpdate()
              },
              fail: function (e) {
                console.log(e)
              }
            })
          },
          error : function(e){
            console.log(e);
          }
        });
      },
      sub(){
        return new Promise((resolve,reject)=>{
          let that = this
          uni.requestSubscribeMessage({
            tmplIds: ['Q7WMU7T1MN7kgKvdlV_LeXtTWzFBJgl21gahavSmMLc'],
            success (res) {
              that.$u.toast("消息订阅成功")
              resolve()
            },
            fail(e) {
              console.log(e)
              reject()
            }

          })
		  })

      },
    }
  }
</script>

<style>
  .uni-container {
    padding: 15px;
  }

  .uni-input-border,
  .uni-textarea-border {
    width: 100%;
    font-size: 14px;
    color: #666;
    border: 1px #e5e5e5 solid;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .uni-input-border {
    padding: 0 10px;
    height: 35px;

  }

  .uni-textarea-border {
    padding: 10px;
    height: 80px;
  }

  .uni-button-group {
    margin-top: 50px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
  }

  .uni-button {
    width: 184px;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
    line-height: 1;
    margin: 0;
    margin-left: 10px;
  }
</style>
